<?php
class Admin_goldens_Controller extends Template_Controller {
	
	public $search;
	public $template = 'admin/index';
	
    public function __construct()
    {
        parent::__construct();
        
        $this->search = array('keyword' => '','page' => 0);
        
        $this->_get_submit();
    }
    
	public function __call($method, $arguments)
	{
		// Disable auto-rendering
		$this->auto_render = FALSE;
	}
	
	function _get_submit()
	{
		if($this->session->get('error_msg'))
			$this->template->error_msg = $this->session->get('error_msg');
		if($this->session->get('warning_msg'))
			$this->template->warning_msg = $this->session->get('warning_msg');
		if($this->session->get('success_msg'))
			$this->template->success_msg = $this->session->get('success_msg');
		if($this->session->get('info_msg'))
			$this->template->info_msg = $this->session->get('info_msg');
		if($this->session->get('frm'))			
			$this->template->content->mr = $this->session->get('frm');
	}
	
    public function index()
    {	
        $this->showlist();
    }
    
    private function _list_language()
    {
		$model_lang = new Language_Model();		
		$this->template->content->list_language = $model_lang->get_with_active();
	}
	public function _show_goldens_type($id='')
	{
		if($id)
			$this->db->where('goldens_type.goldens_type_id',$id);
		$model = new Goldens_type_Model();    	
    	$mlist = $model->get();
    	for($i=0; $i<count($mlist); $i++)
		{
			$model_lang = new Language_Model();			
			$list_lang = $model_lang->get_with_active();
			for($j=0; $j<count($list_lang); $j++)
			{
				$model_content = new Goldens_type_content_Model();
				$this->db->where('goldens_type_id',$mlist[$i]['goldens_type_id']);
				$this->db->where('languages_id',$list_lang[$j]['languages_id']);
				$list = $model_content->get();
				//$list = $model_content->get($mlist[$i]['goldens_id'],$list_lang[$j]['languages_id']);
				if($list){
				$list = array_merge($mlist[$i],$list[0]);				
				}	
				$list_lang[$j] = $list;	
			}
			$mlist[$i]['languages'] = $list_lang;
		}
		return $mlist;
	}
	public function _show_goldens($id='')
	{
		if($id)
			$this->db->where('goldens.goldens_id',$id);
		$model = new Goldens_Model();    	
    	$mlist = $model->get();
    	for($i=0; $i<count($mlist); $i++)
		{
			$model_lang = new Language_Model();			
			$list_lang = $model_lang->get_with_active();
			for($j=0; $j<count($list_lang); $j++)
			{
				$model_content = new Goldens_content_Model();
				$this->db->where('goldens_id',$mlist[$i]['goldens_id']);
				$this->db->where('languages_id',$list_lang[$j]['languages_id']);
				$list = $model_content->get();
				//$list = $model_content->get($mlist[$i]['goldens_id'],$list_lang[$j]['languages_id']);
				if($list){
				$list = array_merge($mlist[$i],$list[0]);				
				}	
				$list_lang[$j] = $list;	
			}
			$mlist[$i]['languages'] = $list_lang;
		}
		return $mlist;
	}
	
    public function showlist()
    {
    	$this->template->content = new View('admin_goldens/list');
    		
		//Assign
		$this->template->content->keyword = $this->search['keyword'];
		
		$this->where_sql();
		
		//Pagination
    	$this->pagination = new Pagination(array(
    		'base_url'    => 'admin_goldens/search/',
		    'uri_segment'    => 'page',
		    'total_items'    => ORM::factory('goldens')->count_all(),
		    'items_per_page' => $this->site['site_num_line2'],
		    'style'          => 'classic',
		));
		$this->db->limit($this->pagination->items_per_page,$this->pagination->sql_offset);
    	
    	$this->where_sql();
    	$mlist = $this->_show_goldens();
    	$this->template->content->mlist = $mlist;
		
    	$this->_list_language();
    	$this->_get_submit();
    }
    
    public function where_sql()
    {
    	if($this->search['keyword'])
    		$this->db->like('goldens_title',$this->search['keyword']);
    }
    
    public function search()
    {    	
    	//Get    	
    	if($this->session->get('sess_search')){			
			$this->search = $this->session->get('sess_search');
		}
		
		$keyword = $this->input->post('txt_keyword');
		if(isset($keyword)){    		
			$this->search['keyword'] = $keyword;
		}
		
		//Page
		$page = $this->uri->segment('page');
		if($page)
			$this->search['page'] = $page;
			
		//Set
		$this->session->set_flash('sess_search',$this->search);
		
		$this->showlist();
    }
    
    public function create()
    {
    	$this->template->content = new View('admin_goldens/frm');
    	$this->_list_language();
		$this->template->content->mListType = $this->_show_goldens_type();
    }
    
    public function edit($id)
    {	
    	$this->template->content = new View('admin_goldens/frm');
    	$this->_list_language();
    	$list = $this->_show_goldens($id);
		$mr = $list[0]['languages'];
		$this->template->content->mr = $mr;
		$this->template->content->mListType = $this->_show_goldens_type();
    }
    
    private function _get_record()
    {
    	$form = array
	    (
	    	'hd_id'	=> '',
	    	'txt_sort_order' => '',
	        'sel_status' => '',
			'txt_link'=>'',
			'txt_goldens_type'=>'',
	    );
		
		$model_lang = new Language_Model();
		$list = $model_lang->get_with_active();	
		for($i=0; $i<count($list); $i++)
		{
			$form['txt_title'.$list[$i]['languages_id']] = '';
			$form['txt_image'.$list[$i]['languages_id']] = '';
			
		}
	 
		$errors = $form;
		
		if($_POST)
    	{
    		$post = new Validation($_POST);
    		
			$post->pre_filter('trim', TRUE);
			for($i=0; $i<count($list); $i++){
				$post->add_rules('txt_title'.$list[$i]['languages_id'],'required');
				
			}
				
			if($post->validate())
 			{
 				$form = arr::overwrite($form, $post->as_array());
 				return $form; 				
			} else {
				$errors = arr::overwrite($errors, $post->errors('goldens_validation'));
				$str_error = '';
	            for($i=0; $i<count($list); $i++)
				{
					if ($errors['txt_title'.$list[$i]['languages_id']])
						$str_error .= $errors['txt_title'.$list[$i]['languages_id']].'<br>';
				}
				
				$this->session->set_flash('error_msg',$str_error);
				
				$hd_id = $this->input->post('hd_id');
				if($form['hd_id'])
					url::redirect('admin_goldens/edit/'.$form['hd_id']);
				else
					url::redirect('admin_goldens/create');
				die();
			}
        }
    }
    private function _get_image($name,$l='')
	{
		//============Upload==============================	
		// uses Kohana upload helper	
		
		//$_FILES = Validation::factory($_FILES)
			//->add_rules($name, 'upload::valid', 'upload::type[gif,jpg,png]', 'upload::size[1M]');
		if($l==1){
			$dir="vn/";
		}elseif($l==2){
			$dir="en/";
		}else{
			$dir="icon/";
		}	
		if ($_FILES[$name]['error']==0)
		{
			//delete file if have upload image
			//if(file_exists($path_filedel)) unlink($path_filedel);
			 $namefile = $_FILES[$name]['name'];
			// Temporary file name
			$filename = upload::save($name,$namefile);
			
			// Resize, sharpen, and save the image
			//print_r($_FILES['txt_image']);
			//exit();
			//echo $filename.'/';
			//unlink(DOCROOT.'uploads/gallery/'.$dir.basename($filename));
			Image::factory($filename)
				//->resize(250, 250,Image::AUTO)
				->save(DOCROOT.'uploads/gallery/'.$dir.basename($filename));
		 	// Remove the temporary file
			
		 	//echo basename($filename).'/';
			//die();
			// Redirect back to the account page
			return basename($filename);
		} else {
			if(!empty($l)){
			$hd_old_image = $this->input->post('hd_old_image'.$l);
			
			}else{
			$hd_old_image = $this->input->post('hd_old_image');
			}
			if ($hd_old_image)
				return $hd_old_image;
			else
				return '';
		}
	}
    private function _save_goldens($hd_id,$record)
    {
		if(!$hd_id){
			$result = ORM::factory('goldens');
			$result->goldens_create_date = time();
		} else {
			$result = ORM::factory('goldens',$hd_id);
		}
		$result->goldens_sort_order = $record['txt_sort_order'];
		$result->goldens_status = $record['sel_status'];
		$result->goldens_icon =  $this->_get_image('txt_image_icon');
		$result->goldens_update_date = time();
		$result->goldens_type_id = $record['txt_goldens_type'];
		
		$hd_id = $result->save();
		return $hd_id;
	}
	
	private function _save_goldens_content($hd_id,$record)
	{
		$model_lang = new Language_Model();
		$list = $model_lang->get_with_active();
			
		for($i=0; $i<count($list); $i++)
		{
			$model_goldens_content = new Goldens_content_Model();
			$result = $model_goldens_content->get($hd_id,$list[$i]['languages_id']);
 
			if($result)
			{
				$this->db->update('goldens_content', 
					array('goldens_title' => $record['txt_title'.$list[$i]['languages_id']] ),
					array('goldens_image' => $this->_get_image('txt_image'.$list[$i]['languages_id'],$list[$i]['languages_id']) ), 
					
					array('goldens_id' => $hd_id,
						  'languages_id' => $list[$i]['languages_id'])
					);
			} else {
				$this->db->insert('goldens_content',									
					array('goldens_id' => $hd_id,
						  'languages_id' => $list[$i]['languages_id'],
						  'goldens_title' => $record['txt_title'.$list[$i]['languages_id']],
						  'goldens_image' => $this->_get_image('txt_image'.$list[$i]['languages_id'],$list[$i]['languages_id'])
						  
						)
				);
			}
		}
		
	}
	
    public function save()
    {
    	$hd_id = $this->input->post('hd_id');
    	
    	$record = $this->_get_record();
		
		if($record)
		{
			$hd_id1 = $this->_save_goldens($hd_id,$record);
			$this->_save_goldens_content($hd_id1,$record);
			
			if(!$this->input->post('hd_id'))
				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_add'));
			else
				$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
		}
		url::redirect('admin_goldens');
		die();    	
    }
    
    public function saveall()
    {
    	$arr_id = $this->input->post('chk_id');
		
		if(is_array($arr_id)){
			$sel_action = $this->input->post('sel_action');
		
			if($sel_action == 'delete')	{
				$id = ORM::factory('goldens')->delete_all($arr_id);
				if($id)
					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));
			} elseif($sel_action == 'block') {
				foreach($arr_id as $arr => $id){
					$result = ORM::factory('goldens',$id);
			    	$result->goldens_status = 0;
			    	$id = $result->save();
		    	}
		    	if($id)
					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
			} elseif($sel_action == 'active')
			{
				foreach($arr_id as $arr => $id){
					$result = ORM::factory('goldens',$id);
			    	$result->goldens_status = 1;
			    	$id = $result->save();
		    	}
		    	if($id)
					$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_save'));
			}			
		} else {
			$this->session->set_flash('warning_msg',Kohana::lang('errormsg_lang.msg_data_error'));
		}
		url::redirect('admin_goldens/search');		
		die();
    }
    
    public function delete($id)
    {
    	$status = $this->db->delete('goldens',array('goldens_id' => $id));
		$status = $this->db->delete('goldens_content',array('goldens_id' => $id));
    	if(count($status)>0)
		{
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_data_del'));
		}
    	url::redirect('admin_goldens/search');
    	die();
    }
    public function delete_image($id)
	{
		$this->db->select();
		$this->db->from('goldens');
		$this->db->where('goldens_id',$id);
		$model = $this->db->get();
		$arrVideos = $model->result_array(false);
		$imageName= $arrVideos[0]['goldens_image'];
		if($imageName)
		{
			$path_filedel = './uploads/goldens/'.$imageName;
		} 
			
		if($path_filedel)
		{
			if(file_exists($path_filedel)) unlink($path_filedel);
						
		}
		
		$result = ORM::factory('goldens',$id);
		$result->goldens_image = '';
		$result->save();
		url::redirect('admin_goldens/edit/'.$id); 
	}
    public function setstatus($id,$status)
    {
    	$status = $this->db->update('goldens',array('goldens_status' => $status),array('goldens_id' => $id));
    	if(count($status)>0)
		{
			$this->session->set_flash('success_msg',Kohana::lang('errormsg_lang.msg_status_change'));
		}
    	url::redirect('admin_goldens/search'); 
    	die();
    }
}
?>